<template>
  <CloudDialog
    v-model:visible="visible"
    title="创建账户"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-close="handleClose">
    <a-form ref="formRef" layout="vertical" :model="formState" :rules="rules">
      <a-form-item label="邮箱" field="email" hide-asterisk>
        <a-input v-model="formState.email" placeholder="请输入邮箱"></a-input>
      </a-form-item>
      <a-form-item label="证书品牌" field="brand" hide-asterisk>
        <a-select
          v-model="formState.brand"
          :options="LicenseBrandOptions"
          placeholder="请选择颁发证书品牌"></a-select>
      </a-form-item>
      <a-form-item label="密钥算法" field="algorithm" hide-asterisk>
        <a-select
          v-model="formState.algorithm"
          placeholder="请选择密钥算法"
          :options="LicenseAlgorithmOptions"></a-select>
      </a-form-item>
    </a-form>
  </CloudDialog>
</template>
<script lang="ts" setup>
import type { AcmeCreateParams } from '@/apis/model/license'
import { addApiAcmeAccountApi } from '@/apis/modules/license'
import { LicenseAlgorithmOptions, LicenseBrandOptions } from '@/constants'
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = reactive<AcmeCreateParams>({
  email: '',
  algorithm: 1,
  brand: 1
})
const emit = defineEmits(['reload'])
const rules: Record<string, FieldRule> = {
  email: {
    required: true,
    validator(value, callback) {
      if (!value) {
        return callback('请输入邮箱')
      }
      if (!regexpMap.email.test(value)) {
        return callback('邮箱格式不正确')
      }
      callback()
    }
  },
  brand: { required: true, message: '请选择证书品牌' },
  algorithm: { required: true, message: '请选择密钥算法' }
}
const handleSubmit = async () => {
  const error = await formRef.value?.validate()
  if (error) return false
  return addApiAcmeAccountApi(formState).then(() => {
    ToastUtils.success('操作成功')
    visible.value = false
    emit('reload')
  })
}
const handleClose = () => {
  formRef.value?.resetFields()
}
</script>
